﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using AviagePortal.Entity;
using System.Collections.Specialized;
// Call example   http://msstoresp12013/sites/ap/_layouts/15/AviagePortal/SubmitPage.aspx
namespace AviagePortal.Layouts
{
    public partial class SubmitPage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {   
            // SPUtility.SendEmail(SPContext.Current.Web, true, true, "v-abchen@microsoft.com", "please approve ","Test approve request mail");            
            this.ErrorLabel.Visible = false;
            this.SubmitPanel.Visible = false;
            this.ApproveRecordPanel.Visible = false;
            this.MessagePanel.Visible = false;
            // this.ErrorMessageLiteral.Visible = false;
            SPGroup editorGroup = SPContext.Current.Web.SiteGroups["AviagePortalEditor"];
            if (!editorGroup.ContainsCurrentUser)
            {
                this.ErrorLabel.Visible = true;
            }
            else
            {
               // Check if there already have a pending approve record
             
                SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
                SPQuery spQuery = new SPQuery();
                spQuery.Query = string.Format(@"<Where>
                        <Eq>
                             <FieldRef Name='Status' />
                             <Value Type='Text'>{0}</Value>
                        </Eq>
                    </Where>", ApproveStatus.Pending);
                SPListItemCollection items = approveRecords.GetItems(spQuery);
                if (items.Count > 0)
                {
                    this.ApproveRecordPanel.Visible = true;
                    // There already have a pending request, you need to cancle it before you submit a new one
                    int length = "<div class=\"ExternalClass201E51BB23DD4D7D9CDCFE1379A784AA\">".Length;
                    ApproveRecordPanelChangeDiscriptionTextArea.InnerHtml = ("" + items[0]["ChangeDescription"]).Substring(length).Replace("</div>", "");
                    // Submitted by Abraham Cheng at 2014/03/29
                    ApproveRecordPanelCreateByLabel.Text = string.Format("Submitted by {0} at {1}", (new SPFieldUserValue(SPContext.Current.Web, "" + items[0]["Created By"])).LookupValue, "" + items[0]["Created"]);
                }
                else
                {
                    this.SubmitPanel.Visible = true;
                }
            }           
        }

        protected void SubmitButton_Click(object sender, EventArgs e)        
        {
            SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
            SPQuery spQuery = new SPQuery();
            spQuery.Query = string.Format(@"<Where>
                        <Eq>
                             <FieldRef Name='Status' />
                             <Value Type='Text'>{0}</Value>
                        </Eq>
                    </Where>", ApproveStatus.Pending);
            SPListItemCollection items = approveRecords.GetItems(spQuery);

            string mailBody = string.Empty;
            if (items.Count == 0)
            {
                try
                {
                    SiteDataOperator.SubmitAll();               
                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    SPListItem newItem = approveRecords.AddItem();
                    newItem["Title"] = "Approve request submit by " + SPContext.Current.Web.CurrentUser.Name;
                    newItem["ChangeDescription"] = ChangeDiscriptionTextArea.InnerText;
                    newItem["Status"] = ApproveStatus.Pending;
                    newItem.Update();

                    // Send mail to approvers, and cc to "AviagePortalEditor"
                    try
                    {
                        mailBody = string.Format(@"<Div>Dear approvers:</Div>
                                                  <Div>{0} submit a change request and waiting for your approving</Div>
                                                  <Div>Change descriptin is:</Div>
                                                  <Div>{1}</Div>
                                                  <Div>You can view this request detail by clicking this link: <a href='{2}'>{2}</a></Div><br/><br/> 
                                                  <Div>This mail is send by workflow automatily, please don't reply it. </Div>", 
                                                  SPContext.Current.Web.CurrentUser.Name,
                                                  "" + newItem["ChangeDescription"],
                                                  SPContext.Current.Web.Url + "/_layouts/15/AviagePortal/ApprovePage.aspx?recordId=" + newItem.ID);
                        if (string.IsNullOrWhiteSpace(Helper.ApproveUsersEmail))
                        {
                            // Haven't found any approver with email adress
                            this.ErrorMessageLiteral.InnerHtml = "Request submit successed， but  Haven't found any approver with email adress，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
                            this.ErrorMessageLiteral.Visible = true;
                        }
                        else
                        {
                           
                            bool result = Helper.SendMail(Helper.ApproveUsersEmail, Helper.EditorUsersMail, "" +newItem["Title"], mailBody);

                            if (!result)
                            {
                                this.ErrorMessageLiteral.Visible = true;
                                this.ErrorMessageLiteral.InnerHtml = "Request submit successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
                            }
                        }                       
                     
                    }
                    catch (Exception ex)
                    {
                        // ErrorMessageLiteral.text
                        this.ErrorMessageLiteral.Visible = true;
                        this.ErrorMessageLiteral.InnerHtml = "Request submit successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
                    }

                    this.Page_Load(null, null);
                }
                catch (Exception ex)
                {

                }
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            SiteDataOperator.CancelAll();
            SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
            SPQuery spQuery = new SPQuery();
            spQuery.Query = string.Format(@"<Where>
                        <Eq>
                             <FieldRef Name='Status' />
                             <Value Type='Text'>{0}</Value>
                        </Eq>
                    </Where>", ApproveStatus.Pending);
            SPListItemCollection items = approveRecords.GetItems(spQuery);
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            string mailBody = string.Empty;
            foreach (SPListItem item in items)
            {
                SPListItem currentItem = approveRecords.GetItemById(item.ID);
                currentItem["Status"] = ApproveStatus.Canceled;
                currentItem.Update();

                mailBody = string.Format(@"<Div>Dear approvers:</Div>
                                                  <Div>{0} cancel the request:</Div>
                                                  <Div>Change descriptin is:</Div>
                                                  <Div>{1}</Div>
                                                  <Div>You can view this request detail by clicking this link: <a href='{2}'>{2}</a></Div><br/><br/> 
                                                  <Div>This mail is send by workflow automatily, please don't reply it. </Div>",
                                            SPContext.Current.Web.CurrentUser.Name,
                                            "" + currentItem["ChangeDescription"],
                                            SPContext.Current.Web.Url + "/_layouts/15/AviagePortal/ApprovePage.aspx?recordId=" + currentItem.ID);
            }

            // Send mail
            try
            {
                if (string.IsNullOrWhiteSpace(Helper.ApproveUsersEmail))
                {
                    this.ErrorMessageLiteral.Visible = true;
                    this.ErrorMessageLiteral.InnerHtml = "Cancel successed，but can't find any editor's email aderss，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
                }
                else if (!string.IsNullOrWhiteSpace(mailBody))
                {
                    bool result = Helper.SendMail(Helper.ApproveUsersEmail, Helper.EditorUsersMail,SPContext.Current.Web.CurrentUser.Name + " canceled the request", mailBody);

                    if (!result)
                    {
                        this.ErrorMessageLiteral.Visible = true;
                        this.ErrorMessageLiteral.InnerHtml = "Cancel successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
                    }
                }
            }
            catch (Exception ex)
            {
                this.ErrorMessageLiteral.Visible = true;
                this.ErrorMessageLiteral.InnerHtml = "Cancel successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.ApproveUsers + ":<br>" + mailBody;
            }

            this.Page_Load(null, null);
        }
    }
}
